package com.wosai.teach.adapter;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.lidroid.xutils.BitmapUtils;
import com.wosai.teach.R;
import com.wosai.teach.cst.C;
import com.wosai.teach.entity.Experiment;
import com.wosai.teach.utils.AppGlobal;
import com.wosai.teach.utils.AppUtil;
import com.wosai.teach.utils.BitmapHelp;

/**
 * @author : qiumy
 * @e-mail : qiumy@wosaitech.com
 * @date : 2015-3-31 下午2:04:10
 * @desc :
 */
public class CacheAdapter extends BaseAdapter {
	private LayoutInflater mInflater;
	private List<Experiment> list;
	private BitmapUtils bitmapUtils;
	private Activity activity;
	/**
	 * 显示左边的选择按钮
	 */
	private boolean showChoose;

	private Map<String, ViewHolder> vhMap = new HashMap<String, CacheAdapter.ViewHolder>();

	public CacheAdapter(Activity activity, List<Experiment> list) {
		this.mInflater = LayoutInflater.from(activity);
		this.list = list;
		this.activity = activity;
		bitmapUtils = BitmapHelp.getBitmapUtils(activity);
		bitmapUtils.configDefaultLoadingImage(R.drawable.icon);
		bitmapUtils.configDefaultLoadFailedImage(R.drawable.icon);
	}

	public void setList(List<Experiment> list) {
		this.list = list;
	}

	public void addList(List<Experiment> list) {
		this.list.addAll(list);
	}

	@Override
	public int getCount() {
		return list == null ? 0 : list.size();
	}

	@Override
	public Object getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.cache_item, parent, false);
			holder = new ViewHolder();
			holder.cacheIcon = (ImageView) convertView
					.findViewById(R.id.cache_icon);
			holder.cacheName = (TextView) convertView
					.findViewById(R.id.cache_name);
			holder.cacheOp = (TextView) convertView.findViewById(R.id.cache_op);
			holder.cacheRound = (ImageView) convertView
					.findViewById(R.id.cache_round);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		final Experiment exp = list.get(position);
		holder.exp = exp;
		bitmapUtils.display(holder.cacheIcon, exp.getIcon1());
		holder.cacheName.setText(exp.getExpName());
		holder.cacheOp.setText("卸载");
		showChooseByVH(holder);
		holder.cacheOp.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				unInstall(exp);
			}
		});
		String key = exp.getExpId() + "";
		if (!vhMap.containsKey(key)
				|| vhMap.get(key).hashCode() != holder.hashCode()) {
			vhMap.put(exp.getExpId() + "", holder);
		}
		return convertView;
	}

	/**
	 * 出现选择按钮
	 */
	public void showChoose(boolean show) {
		showChoose = show;
		Iterator<String> it = vhMap.keySet().iterator();
		while (it.hasNext()) {
			String key = it.next();
			ViewHolder vh = vhMap.get(key);
			showChooseByVH(vh);
		}
	}

	/**
	 * 显示/隐藏右边的选择按钮
	 */
	public void showChooseByVH(ViewHolder vh) {
		if (showChoose) {
			vh.cacheRound.setVisibility(View.VISIBLE);
			vh.cacheOp.setVisibility(View.GONE);
		} else {
			vh.cacheRound.setVisibility(View.GONE);
			vh.cacheOp.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * 选择
	 */
	public void choose(ViewHolder vh) {
		vh.choose = !vh.choose;
		if (vh.choose) {
			vh.cacheRound.setBackgroundResource(R.drawable.chose);
		} else {
			vh.cacheRound.setBackgroundResource(R.drawable.unchose);
		}
	}

	/**
	 * 选择
	 */
	public void chooseAll(boolean choose) {
		Iterator<String> it = vhMap.keySet().iterator();
		while (it.hasNext()) {
			String key = it.next();
			ViewHolder vh = vhMap.get(key);
			if (choose) {
				vh.cacheRound.setBackgroundResource(R.drawable.chose);
				vh.choose = true;
			} else {
				vh.cacheRound.setBackgroundResource(R.drawable.unchose);
				vh.choose = false;
			}
		}
	}

	/**
	 * 卸载选择的软件
	 */
	public void unInstallChoose() {
		Iterator<String> it = vhMap.keySet().iterator();
		while (it.hasNext()) {
			String key = it.next();
			ViewHolder vh = vhMap.get(key);
			if (vh.choose) {
				Experiment exp = vh.exp;
				PackageInfo pi = AppUtil
						.getPackageInfo(exp.getApkPackageName());
				int ver = AppUtil.getVersionCode(pi);
				if (ver > 0) {
					unInstall(exp);
				} else {
					vhMap.remove(key);
				}
			}
		}
	}

	/**
	 * 判断是否没有被选择
	 */
	public boolean checkNoChoose() {
		Iterator<String> it = vhMap.keySet().iterator();
		while (it.hasNext()) {
			String key = it.next();
			ViewHolder vh = vhMap.get(key);
			if (vh.choose) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 卸载软件
	 */
	private void unInstall(Experiment exp) {
		Uri packageURI = Uri.parse("package:" + exp.getApkPackageName()); // 包名
		Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
		activity.startActivityForResult(uninstallIntent,
				C.REQUEST_CODE_UNINSTALL);
		AppGlobal.simulationRefresh = true;
		// 删除 apk
		String sdcard = Environment.getExternalStorageDirectory().getPath();
		File tmpFile = new File(sdcard + "/teach_platform");
		if (!tmpFile.exists()) {
			return;
		}
		String tt[] = exp.getApkURL().split("/");
		String fileName = tt[tt.length - 1];
		String savePath = sdcard + "/teach_platform/" + fileName;
		File apk = new File(savePath);
		if (apk.exists() && apk.isFile()) {
			apk.delete();
		}
	}

	/**
	 * @author : qiumy
	 * @e-mail : qiumy@wosaitech.com
	 * @date : 2015-4-2 上午10:35:43
	 * @desc :
	 */
	public class ViewHolder {
		public ImageView cacheIcon;

		public TextView cacheName;

		public TextView cacheOp;

		public ImageView cacheRound;

		public boolean choose;

		public Experiment exp;
	}

}
